<template>
<div class="personal-card">
    <el-row :gutter="24">
        <el-col :span="5">
            <el-card shadow="never" class="user-card">
                <div class="user-info">
                    <img :src=userInfo.userProfile class="user-avator" alt />
                    <div class="user-info-cont">
                        <div class="user-info-name">{{ userInfo.userName }}</div>
                        <p>{{ userInfo.userDesc }}</p>
                    </div>
                </div>
            </el-card>
        </el-col>
        <el-col :span="18">
            <el-tabs type="card">
                <el-tabs v-model="activePanel">
                    <el-tab-pane class="panel" label="用户信息" name="first">
                        <el-form label-width="80px" style="width: 40%;">
                            <el-form-item label="用户名">
                                <el-input v-model=userInfo.userName :disabled=editable></el-input>
                            </el-form-item>
                            <el-form-item label="密码">
                                <el-input v-model=userInfo.userPassword :disabled=editable></el-input>
                            </el-form-item>
                            <el-form-item label="联系方式">
                                <el-input v-model=userInfo.userPhone :disabled=editable></el-input>
                            </el-form-item>
                            <el-form-item label="性别">
                                <el-input v-model=userInfo.userSex :disabled=editable></el-input>
                            </el-form-item>
                            <el-form-item label="年龄">
                                <el-input v-model=userInfo.userAge :disabled=editable></el-input>
                            </el-form-item>
                            <el-form-item label="个人介绍">
                                <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 8}" v-model=userInfo.userDesc :disabled=editable></el-input>
                            </el-form-item>
                            <el-form-item label="修改头像" v-if="!editable">
                                <el-upload
                                    class="avatar-uploader"
                                    action="http://localhost:8080/uploadUserProfile"
                                    list-type="picture-card"
                                    :show-file-list="true"
                                    :on-preview="handlePictureCardPreview"
                                    :on-remove="handleRemove"
                                    :auto-upload="false"
                                    ref="upload"
                                    :on-success="onSuccess"
                                    :on-progress="onProgress"
                                    :limit="1"
                                    >
                                    <i class="el-icon-plus"></i>
                                </el-upload>
                                <el-dialog :visible.sync="dialogVisible">
                                    <img width="100%" :src="imgURL" alt="">
                                </el-dialog>
                            </el-form-item>
                        </el-form>
                        <el-row class="manageUser-toolbar" style="text-align:left;">
                            <el-button v-if=editable type="primary" icon="el-icon-edit" @click="onModify()" :disabled=!editable>修改信息</el-button>
                            <el-button v-else type="primary" icon="el-icon-arrow-left" @click="onCancel()" :disabled=editable>放弃修改</el-button>
                            <el-button type="success" icon="el-icon-check" @click="onSubmitEdit()" :disabled=editable>提交修改</el-button>
                        </el-row>
                    </el-tab-pane>
                    <el-tab-pane class="panel" label="订单管理" name="second">
                        <div class="order-table-container">
                            <el-table
                                :data="orderList"
                                style="width: 100%"
                                border
                                :header-cell-style="tableHeaderStyle"
                                class="order-table">
                                <el-table-column prop="orderID" label="订单ID" width="80" fixed="left"></el-table-column>
                                <el-table-column prop="orderType" label="订单类别" width="120" fixed="left"></el-table-column>
                                <el-table-column prop="orderPrice" label="订单金额" width="100">
                                    <template slot-scope="scope">
                                        {{ scope.row.orderPrice }} 元
                                    </template>
                                </el-table-column>
                                <el-table-column prop="orderNum" label="数量" width="80"></el-table-column>
                                <el-table-column prop="orderDate" label="下单时间" width="180"></el-table-column>
                                <el-table-column prop="orderStartDate" label="开始日期" width="180"></el-table-column>
                                <el-table-column prop="orderEndDate" label="结束日期" width="180"></el-table-column>
                                <el-table-column prop="orderCode" label="消费凭证" width="300"></el-table-column>
                                <el-table-column prop="orderRefund" label="退款状态" width="100">
                                    <template slot-scope="scope">
                                        <el-tag type="success" v-if="scope.row.orderRefund !== 0">已退款</el-tag>
                                        <el-tag type="info" v-else>未退款</el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="orderRefundDate" label="退款日期" width="180">
                                    <template slot-scope="scope">
                                        {{ scope.row.orderRefundDate || '无' }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" width="120" fixed="right">
                                    <template slot-scope="scope">
                                        <el-button
                                            size="mini"
                                            type="danger"
                                            @click="handleRefund(scope.row)"
                                            v-if="scope.row.orderRefund === 0">申请退款</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>

                            <!-- 分页组件 -->
                            <div class="pagination-container">
                                <el-pagination
                                    @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange"
                                    :current-page="pagination.currentPage"
                                    :page-sizes="[5, 10, 20, 50]"
                                    :page-size="pagination.pageSize"
                                    layout="total, sizes, prev, pager, next, jumper"
                                    :total="pagination.total">
                                </el-pagination>
                            </div>
                        </div>

                        <!-- 退款确认对话框 -->
                        <el-dialog
                            title="退款确认"
                            :visible.sync="refundDialogVisible"
                            width="30%">
                            <div v-if="currentOrder">
                                <p><strong>订单ID：</strong>{{ currentOrder.orderID }}</p>
                                <p><strong>订单类别：</strong>{{ currentOrder.orderType }}</p>
                                <p><strong>订单金额：</strong>{{ currentOrder.orderPrice }} 元</p>
                                <p><strong>下单时间：</strong>{{ currentOrder.orderDate }}</p>
                                <p><strong>数量：</strong>{{ currentOrder.orderNum }}</p>
                                <p class="warning-text">确认要对此订单申请退款吗？</p>
                            </div>
                            <span slot="footer" class="dialog-footer">
                                <el-button @click="refundDialogVisible = false">取 消</el-button>
                                <el-button type="primary" @click="confirmRefund">确 认</el-button>
                            </span>
                        </el-dialog>
                    </el-tab-pane>
<!--                    <el-tab-pane class="panel" label="游记管理" name="third">暂无游记</el-tab-pane>-->
                    <el-tab-pane class="panel" label="账号管理" name="fourth">
                        <el-button type="danger" icon="el-icon-s-promotion" @click="quit()">退出账号</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-tabs>
        </el-col>
    </el-row>

</div>
</template>

<script>
const axios = require('axios')
const qs = require('qs')
const ele = require('element-ui')

export default {
    name: 'personal_page',
    data() {
        return {
            activePanel: "first",
            editable: true,
            userName: '',
            userInfo: {},
            dialogVisible: false,
            imgURL: '',
            // 订单管理相关数据
            orderList: [],
            refundDialogVisible: false,
            currentOrder: null,
            // 分页相关
            pagination: {
                currentPage: 1,
                pageSize: 10,
                total: 0
            }
        }
    },
    methods: {
        quit() {
            window.localStorage.setItem('userName', '');
            window.localStorage.setItem('userType', '');
            window.localStorage.setItem('userProfile', '');
            // 触发自定义事件通知App.vue更新状态
            window.dispatchEvent(new CustomEvent('userStateChanged'));
            this.$router.push('/');
            ele.Message.success("退出登录成功");
        },
        onModify() {
            this.editable = false
        },
        onProgress() {

        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePictureCardPreview(file) {
            this.imgURL = file.url
        },
        onSubmitEdit(res) {
            // 首先上传用户头像，获得头像在服务器上的保存地址
            // 如果头像上传成功，会自动调用onSuccess
            this.$refs.upload.submit();
        },
        onSuccess: function (response) {
            if (response.status === "success") {
                this.userInfo.userProfile = response.imgURL
                // 更新用户信息
                let _this = this
                axios({
                    method: 'post',
                    url: 'http://localhost:8080/updateUser',
                    headers: {
                        'Content-type': 'application/x-www-form-urlencoded'
                    },
                    data: qs.stringify({
                        userID: this.userInfo.userID,
                        userNamePrev: this.userName,
                        userName: this.userInfo.userName,
                        userPassword: this.userInfo.userPassword,
                        userSex: this.userInfo.userSex,
                        userAge: this.userInfo.userAge,
                        userPhone: this.userInfo.userPhone,
                        userDesc: this.userInfo.userDesc,
                        userStatus: this.userInfo.userStatus,
                        userProfile: this.userInfo.userProfile
                    })
                }).then(function (response) {
                    let status = response.data.status
                    if (status == 'failed') {
                        ele.Message.error("该用户名已经被别人占用啦，换一个吧~")
                        _this.userName = window.localStorage.getItem('userName');
                        _this.userInfo.userName = _this.userName
                    } else {
                        ele.Message.success('修改成功')
                        _this.userInfo = response.data.userList
                        _this.userName = _this.userInfo.userName
                        window.localStorage.setItem('userName', _this.userName);
                        _this.editable = true
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            }
            else {
                ele.Message.error("头像上传失败，请重试")
            }
        },
        onCancel() {
            this.editable = true
        },

        // 订单管理相关方法
        // 表格表头样式
        tableHeaderStyle() {
            return {
                background: '#409EFF',
                color: '#fff',
                fontWeight: 'bold',
                fontSize: '14px',
                height: '50px'
            };
        },

        // 处理每页显示数量变化
        handleSizeChange(val) {
            this.pagination.pageSize = val;
            this.pagination.currentPage = 1; // 重置到第一页
            this.loadOrderList();
        },

        // 处理页码变化
        handleCurrentChange(val) {
            this.pagination.currentPage = val;
            this.loadOrderList();
        },

        // 加载订单列表
        loadOrderList() {
            let _this = this;
            axios({
                method: 'get',
                url: 'http://localhost:8080/getOrderList',
                headers: {
                    'Content-type': 'application/x-www-form-urlencoded'
                },
                params: {
                    userName: this.userName,
                    page: this.pagination.currentPage,
                    pageSize: this.pagination.pageSize
                }
            }).then(function(response) {
                if (response.data.status === 'success') {
                    _this.orderList = response.data.dataList || [];
                    // 更新总数据量
                    _this.pagination.total = response.data.total || _this.orderList.length;
                } else {
                    ele.Message.error('获取订单列表失败');
                }
            }).catch(function(error) {
                console.log(error);
                ele.Message.error('获取订单列表失败');
            });
        },

        // 处理退款申请
        handleRefund(order) {
            this.currentOrder = order;
            this.refundDialogVisible = true;
        },

        // 确认退款
        confirmRefund() {
            if (!this.currentOrder) {
                ele.Message.error('订单信息不完整');
                return;
            }

            let _this = this;
            axios({
                method: 'post',
                url: 'http://localhost:8080/refundOrder',
                headers: {
                    'Content-type': 'application/x-www-form-urlencoded'
                },
				params: {
                    userName: this.userName,
                    orderID: this.currentOrder.orderID,
					orderCode: this.currentOrder.orderCode
                }
            }).then(function(response) {
                if (response.data.status === 'success') {
                    ele.Message.success('退款申请成功');
                    _this.refundDialogVisible = false;
                    // 重新加载订单列表
                    _this.loadOrderList();
                } else {
                    ele.Message.error(response.data.message || '退款申请失败');
                }
            }).catch(function(error) {
                console.log(error);
                ele.Message.error('退款申请失败');
            });
        }
    },
    created() {
        if (window.localStorage.getItem('userType') != 'user') {
            ele.Message.error("请先登录，即将跳转到登录页面")
            this.$router.push('/login')
        } else {
            this.userName = window.localStorage.getItem('userName');
            let _this = this
            axios({
                method: 'post',
                url: 'http://localhost:8080/getUser',
                headers: {
                    'Content-type': 'application/x-www-form-urlencoded'
                },
                data: qs.stringify({
                    userName: _this.userName,
                })
            }).then(function (response) {
                let status = response.data.status
                if (status == 'failed') {
                    ele.Message.error("加载用户信息失败")
                } else {
                    _this.userInfo = response.data.userList
                    window.localStorage.setItem('userProfile', response.data.userList.userProfile)
                    // 加载订单列表
                    _this.loadOrderList();
                }
            }).catch(function (error) {
                console.log(error)
            })
        }
    }
};
</script>

<style scoped>
.personal-card {
    padding-left: 50px;
    padding-right: 50px;
    margin-top: 30px;
    width: 100%;
}

.panel {
    padding-top: 20px;
}

.user-avator {
    width: 50px;
    height: 50px;
    border-radius: 50%;
}

.user-info {
    display: flex;
    align-items: flex-start;
    flex-direction: column;
    text-align: center;
}

.user-info-name {
    font-size: 20px;
    margin-top: 10px;
}

.user-info-cont {
    padding-left: 0;
    width: 100%;
}

.user-info-cont p {
    font-size: 12px;
    color: gray;
    //margin-top: 5px;
}

.user-card {
    padding: 15px 10px;
}

/* 订单管理相关样式 */
.warning-text {
    color: #E6A23C;
    font-weight: bold;
    margin-top: 15px;
}

.order-table-container {
    width: 100%;
    overflow: hidden;
}

.order-table {
    margin-bottom: 20px;
}

.pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    margin-bottom: 30px;
}

/* 固定列样式优化 */
.el-table .el-table__fixed-right {
    box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
}

.el-table .el-table__fixed-left {
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
}
</style>
